package main

import (
    "fmt"
    "gowebprog/ch02/chitchat/data"
    "net/http"
)

// GET /login
// 显示login页面
func login(w http.ResponseWriter, r *http.Request) {
    t := parseTemplateFiles("login.layout", "public.navbar", "login")
    t.Execute(w, nil)
}

// GET /signup
// show  the signup page
func signup(w http.ResponseWriter, r *http.Request) {
    generateHTML(w, nil, "login.layout", "public.navbar", "signup")
}

// POST /signupAccount 注册
// create the user account
func signupAccount(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()
    if err != nil {
        danger(err, "cannot parse form")
    }
    user := &data.User{
        Name:     r.PostFormValue("name"),
        Email:    r.PostFormValue("email"),
        Password: r.PostFormValue("password"),
    }
    // fmt.Printf("%#v\n", user)
    if err := user.Create(); err != nil {
        danger(err, "Cannot create user")
    }
    fmt.Printf("%#v\n", err)

    http.Redirect(w, r, "/login", 302)
}

// GET /logout
// Logs the user out
func logout(w http.ResponseWriter, r *http.Request) {
    cookie, err := r.Cookie("_cookie")
    cookie = cookie
    if err != http.ErrNoCookie {
        warning(err, "获取cookies失败")
        // todo  清除session
        // session := data.Session{Uuid: cookie.Value}
        // session.DeleteByUUID()
    }
    http.Redirect(w, r, "/", 302)
}

// POST /authenticate
// Authenticate the user given the email and password
// 认证用户和密码
func authenticate(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()
    user, err := data.UserByEmail(r.PostFormValue("email"))
    fmt.Printf("%v", user)
    if err != nil {
        danger(err, "没有找到此用户")
    }
    // 验证密码
    if user.Password == data.Encrypt(r.PostFormValue("password")) {
        // 创建session
        serrsion, err := user.CreateSession()
        fmt.Printf("%#v",serrsion)
        if err != nil {
            danger(err, "创建session失败")
        }
        cookie := http.Cookie{Name: "_cookie", Value: serrsion.Uuid, HttpOnly: true}
        // 设置cookie
        http.SetCookie(w, &cookie)
        http.Redirect(w, r, "/", 302)
    } else {
        http.Redirect(w, r, "/login", 302)
    }

}
